{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import os\n",
    "from tqdm import tqdm  # 进度条工具\n",
    "%matplotlib inline\n",
    "\n",
    "# 定义信号参数（与MATLAB生成参数一致）\n",
    "Fs = 1e6   # 采样率1MHz\n",
    "N = 1024   # 采样点数\n",
    "\n",
    "# 创建保存目录\n",
    "save_dir = \"Signal_Spectra\"\n",
    "class_names = {\n",
    "    1: 'AM',\n",
    "    2: 'FM',\n",
    "    3: 'Bpsk',\n",
    "    4: 'Qpsk',\n",
    "    5: '16Qam',\n",
    "    6: '64Qam'\n",
    "}\n",
    "\n",
    "# 为每个类别创建子目录\n",
    "for name in class_names.values():\n",
    "    class_dir = os.path.join(save_dir, name)\n",
    "    os.makedirs(class_dir, exist_ok=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def compute_spectrum(signal, Fs=Fs, N=N):\n",
    "    \"\"\"计算单边幅度谱\"\"\"\n",
    "    Y = np.fft.fft(signal)\n",
    "    P2 = np.abs(Y / N)         # 双边谱\n",
    "    P1 = P2[:N//2 + 1]         # 取单边谱\n",
    "    P1[1:-1] *= 2              # 调整幅度（直流分量不调整）\n",
    "    f = Fs * np.arange(N//2 + 1) / N  # 频率轴\n",
    "    return f, P1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# def process_all_signals(csv_path, save_dir, batch_size=100):\n",
    "#     # 读取CSV文件\n",
    "#     df = pd.read_csv(csv_path)\n",
    "    \n",
    "#     # 初始化进度条\n",
    "#     pbar = tqdm(total=len(df), desc=\"Processing signals\")\n",
    "    \n",
    "#     # 分批处理避免内存问题\n",
    "#     for start_idx in range(0, len(df), batch_size):\n",
    "#         batch = df.iloc[start_idx:start_idx+batch_size]\n",
    "        \n",
    "#         for idx, row in batch.iterrows():\n",
    "#             # 提取信号和标签\n",
    "#             signal = row.values[:-1].astype(float)\n",
    "#             label = int(row['Label'])\n",
    "#             class_name = class_names[label]\n",
    "            \n",
    "#             # 计算频谱\n",
    "#             f, P1 = compute_spectrum(signal)\n",
    "            \n",
    "#             # 创建图形\n",
    "#             plt.figure(figsize=(10, 4), dpi=100)\n",
    "#             plt.plot(f, P1)\n",
    "            \n",
    "#             # 去掉标题、X轴、Y轴和网格\n",
    "#             plt.title('')  # 去掉标题\n",
    "#             plt.xlabel('')  # 去掉X轴标签\n",
    "#             plt.ylabel('')  # 去掉Y轴标签\n",
    "#             plt.xticks([])  # 去掉X轴刻度\n",
    "#             plt.yticks([])  # 去掉Y轴刻度\n",
    "#             plt.grid(False)  # 去掉网格\n",
    "            \n",
    "#             # 去掉边框\n",
    "#             plt.gca().spines['top'].set_visible(False)\n",
    "#             plt.gca().spines['right'].set_visible(False)\n",
    "#             plt.gca().spines['bottom'].set_visible(False)\n",
    "#             plt.gca().spines['left'].set_visible(False)\n",
    "            \n",
    "#             # 保存路径\n",
    "#             save_path = os.path.join(save_dir, class_name, \n",
    "#                                    f'{class_name}_sample{idx%200+1:03d}.png')\n",
    "#             plt.savefig(save_path, bbox_inches='tight', pad_inches=0)  # 去掉多余空白\n",
    "#             plt.close()  # 关闭图形释放内存\n",
    "            \n",
    "#             pbar.update(1)\n",
    "    \n",
    "#     pbar.close()\n",
    "def process_all_signals(csv_path, save_dir, batch_size=100):\n",
    "    # 读取CSV文件\n",
    "    df = pd.read_csv(csv_path)\n",
    "    \n",
    "    # 初始化进度条\n",
    "    pbar = tqdm(total=len(df), desc=\"Processing signals\")\n",
    "    \n",
    "    # 分批处理避免内存问题\n",
    "    for start_idx in range(0, len(df), batch_size):\n",
    "        batch = df.iloc[start_idx:start_idx+batch_size]\n",
    "        \n",
    "        for idx, row in batch.iterrows():\n",
    "            # 提取信号和标签\n",
    "            signal = row.values[:-1].astype(float)\n",
    "            label = int(row['Label'])\n",
    "            class_name = class_names[label]\n",
    "            \n",
    "            # 计算频谱\n",
    "            f, P1 = compute_spectrum(signal)\n",
    "            \n",
    "            # ---------- 关键修改部分 ----------\n",
    "            plt.figure(figsize=(2.24, 2.24), dpi=100)  \n",
    "            plt.plot(f, P1)\n",
    "            \n",
    "            # 强制设置坐标轴范围填满整个图像\n",
    "            plt.xlim(f[0], f[-1])  # X轴充满\n",
    "            plt.ylim(0, np.max(P1)*1.05)  # Y轴留有5%余量\n",
    "            \n",
    "            # 去掉所有边距和空白\n",
    "            plt.subplots_adjust(left=0, right=1, bottom=0, top=1)  # 无边界\n",
    "            # -------------------------------\n",
    "            \n",
    "            # 保持原有样式设置（去掉标题、刻度等）\n",
    "            plt.title('')\n",
    "            plt.xlabel('')\n",
    "            plt.ylabel('')\n",
    "            plt.xticks([])\n",
    "            plt.yticks([])\n",
    "            plt.grid(False)\n",
    "            plt.gca().spines['top'].set_visible(False)\n",
    "            plt.gca().spines['right'].set_visible(False)\n",
    "            plt.gca().spines['bottom'].set_visible(False)\n",
    "            plt.gca().spines['left'].set_visible(False)\n",
    "            \n",
    "            # 保存路径\n",
    "            save_path = os.path.join(save_dir, class_name, \n",
    "                                   f'{class_name}_sample{idx%200+1:03d}.png')\n",
    "            plt.savefig(save_path, dpi=100, bbox_inches='tight', pad_inches=0)\n",
    "            plt.close()\n",
    "            \n",
    "            pbar.update(1)\n",
    "    \n",
    "    pbar.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processing signals: 100%|██████████| 1200/1200 [00:26<00:00, 44.46it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "所有频谱图已保存至: g:\\DaTang_VS\\Signal_Spectra\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "# 执行批量处理（约需要5-10分钟）\n",
    "process_all_signals('rf_signals_dataset.csv', save_dir)\n",
    "\n",
    "print(\"所有频谱图已保存至:\", os.path.abspath(save_dir))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "pytorch",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
